package com.example.it.studyactionbartab;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements ActionBar.TabListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[] tabNames = {"收藏", "全部"};

        //使用getSupportActionBar可以有更好的兼容性
        ActionBar actionBar = this.getSupportActionBar();
        //设置当前的导航模式为TAGS模式
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        /*
        * 添加Tab
        * Note: 必须要添加一个回调
        * */
        for (String name : tabNames) {
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(name)
                            .setTabListener(this)
            );
        }
    }

    /*
    * 当选中TAB 时触发的事件
    * */
    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        Fragment fragment = null;
        switch (String.valueOf(tab.getText())) {
            case "收藏":
                fragment = new FragmentCollect();
                break;
            case "全部":
                fragment = new FragmentAll();
                break;
        }
        ft.replace(R.id.activity_main, fragment);
        //ft.commit();
    }

    /*
    * 当 Tab取消选中时触发的事件
    * */
    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
        Toast.makeText(this, "onTabUnselected", Toast.LENGTH_SHORT).show();
    }

    /*
    * 当重复选中TAB时候出发的事件
    * */
    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
        Toast.makeText(this, "onTabReselected", Toast.LENGTH_SHORT).show();
    }
}
